<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * @property int $id
 * @property int $goods_id
 * @property int $uses_id
 * @property string $openid
 * @property int $room_id
 * @property string $order_at
 * @property string $send_at
 * @property int $time_diff
 * @property boolean $send_status
 * @property boolean $notice_status
 * @property int $is_user_eva
 * @property string $updated_at
 * @property string $created_at
 * @property int $num
 */
class RoomSendHis extends Model
{
    const TABLE = 'room_send_his';


    CONST SEND_STATUS_ING = 0;
    CONST SEND_STATUS_FINISH = 1;
    CONST SEND_STATUS_CANCEL = 2;


    /**
     * @var array
     */
    protected $fillable = ['goods_id', 'uses_id', 'openid', 'room_id', 'order_at','send_at','time_diff', 'send_status', 'notice_status','is_user_eva', 'updated_at', 'created_at'];

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;


    public static function getDataByOpenid($openid)
    {
        return DB::table(self::TABLE)
            ->where('openid', $openid)
            ->where('is_user_eva', 0)
            ->get();
    }


    public static function receivedToday($goodId, $openid)
    {
        $date = date('Y-m-d 00:00:00');
        return (int)DB::table(self::TABLE)
            ->where('order_at', '>=', $date)
            ->where('send_status', '<>', 2)
            ->where([
                ['goods_id', $goodId],
                ['openid', $openid],
            ])->sum('num');
    }

    public function add($data)
    {
        $date = date('Y-m-d H:i:s');
        $model = new self();
        $model->goods_id    = $data['goods_id'];
        $model->openid      = $data['openid'];
        $model->room_id     = $data['room_id'];
        $model->num         = $data['num'];
        $model->send_status = self::SEND_STATUS_ING;
        $model->order_at    = $date;
        $model->created_at  = $date;
        return $model->save();
    }

    public function setSendStatus($record, $status)
    {
        $date = date('Y-m-d H:i:s');
        $record->send_status = $status;
        $record->updated_at  = $date;
        if (self::SEND_STATUS_FINISH === $status) {
            $record->send_at = $date;
            $diff = time() - strtotime($record->order_at);
            if ($diff) {
                $record->time_diff = floor($diff / 60);
            }
        }
        return $record->save();
    }


}
